package unipi.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import unipi.database.Department;
import unipi.helpers.HTMLPages;
import unipi.helpers.LoginCookie;
import unipi.helpers.Pair;

public class ViewDpts extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	public ViewDpts()
	{
		super();
	}
	
	public void init() throws ServletException
	{
		
	
	}
	
	private String getPage(String uid)
	{
		String content = "<h1>Τμήματα</h1>";
		
		List<List<String>> rootDpts = Department.getRootDpts();
		
		if(rootDpts == null)
			content += "Πρόβλημα με την φόρτωση των τμημάτων.";
		else
		{			
			content += "<ul class=\"perdepList\">";			
			
			List<Pair<List<String>, Integer>> L = new ArrayList<Pair<List<String>, Integer>>();
			
			for(List<String> root : rootDpts)
			{
				L.add(new Pair<List<String>, Integer>(root, 0));
				List<Pair<List<String>, Integer>> children = Department.getAllChildren(root.get(0)); 
				if(children != null) L.addAll(children);		
			}
			
			int depth;
			int currdepth = 0;
			int openuls = 0;
			for(Pair<List<String>, Integer> pair : L)
			{
				depth = pair.getSecond();
				if(depth > currdepth)
				{
					for(int d = 0; d < depth - currdepth; d++)
					{
						content += "<li class=\"nobullet\"><ul class=\"perdepList\">";
						openuls++;
					}
				}
				else if(depth < currdepth)
				{
					for(int d = 0; d < currdepth - depth; d++)
					{
						content += "</ul></li>";
						openuls--;
					}
				}	
				content += "<li><a href=\"#" + pair.getFirst().get(0) + "\">" + pair.getFirst().get(1) + "</a></li>";
				currdepth = depth;
			}			
	
			for(int x = 0; x < openuls; x++) content += "</ul></li>";
			
			content += "</ul>";
			
			for(Pair<List<String>, Integer> data : L)
			{
				content += "<br/><br/>";
				
				content += "<a name=\"" + data.getFirst().get(0) + "\" /><h3 class=\"companyName\">" +
							data.getFirst().get(1) + "</h3>";
				
				content += data.getFirst().get(2).replaceAll("(\r\n|\n)", "<br />");
				
				content += "<br/><br/>";
			}
		}
		
		return HTMLPages.getGeneralPage(content, uid);	
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		if(!LoginCookie.authCookie(request))
			response.sendRedirect("Login");
		else
		{
			String uid = LoginCookie.Get(request)[0];
			
			response.setContentType("text/html; charset=UTF-8");	
			PrintWriter out = response.getWriter();
			
			out.println(getPage(uid));
			
			out.close();			
		}
	}
	
}
